package com.zhongan.gateway.common.utils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ConsumerConfig;
import com.alibaba.dubbo.config.ReferenceConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.alibaba.dubbo.rpc.service.GenericService;
import com.zhongan.gateway.bean.Api;

public class DubboUtil {

    private static String                      name;

    private static String                      address;

    private static Integer                     timeout;

    private static Map<String, GenericService> services = new ConcurrentHashMap<String, GenericService>();

    public static void deleteServiceCache(int serviceId) {
        if (services != null) {
            services.remove(serviceId);
        }
    }

    public static GenericService getService(Api api) {
        String serviceKey = api.getServiceName() + "_" + api.getVersion();
        GenericService service = services.get(serviceKey);
        if (service != null) {
            return service;
        }

        ApplicationConfig application = new ApplicationConfig();
        application.setName(name);

        RegistryConfig registry = new RegistryConfig();
        registry.setProtocol("zookeeper");
        registry.setAddress(address);

        ConsumerConfig consumer = new ConsumerConfig();
        if (null == api.getTimeout() || api.getTimeout() <= 0) {
            consumer.setTimeout(timeout);
        } else {
            consumer.setTimeout(api.getTimeout());
        }

        consumer.setRetries(0);

        ReferenceConfig<GenericService> referenceConfig = new ReferenceConfig<GenericService>();
        referenceConfig.setApplication(application);
        referenceConfig.setRegistry(registry);
        referenceConfig.setConsumer(consumer);
        referenceConfig.setInterface(api.getInterfaceName());
        referenceConfig.setVersion(api.getVersion());
        referenceConfig.setGeneric(true);
        service = referenceConfig.get();
        if (service != null) {
            services.put(serviceKey, service);
        }

        return service;
    }

    public void setName(String name) {
        DubboUtil.name = name;
    }

    public void setAddress(String address) {
        DubboUtil.address = address;
    }

    public void setTimeout(Integer timeout) {
        DubboUtil.timeout = timeout;
    }
}
